package com.cwz.gateway.service.impl;

import com.cwz.core.captcha.WCaptcha;
import com.cwz.core.constant.CacheConstants;
import com.cwz.core.constant.Constants;
import com.cwz.core.exception.captcha.CaptchaException;
import com.cwz.core.result.R;
import com.cwz.core.utils.string.StringUtils;
import com.cwz.core.utils.uuid.IdUtils;
import com.cwz.gateway.config.properties.CaptchaProperties;
import com.cwz.gateway.service.ValidateCodeService;
import com.cwz.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: w-demo
 * @description: 验证码处理实现
 * @author: Wen
 **/
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
	@Autowired
	private RedisService redisService;
	@Autowired
	private CaptchaProperties captchaProperties;

	@Override
	public R<Map<String, Object>> createCaptcha() throws CaptchaException {
		Map<String, Object> result = new HashMap<>();
		Boolean captchaEnabled = captchaProperties.getEnabled();
		result.put("captchaEnabled", captchaEnabled);
		if (!captchaEnabled) {
			return R.ok(result, "操作成功");
		}
		// 生成验证码
		Map<String, String> map = WCaptcha.require()
			.style(captchaProperties.getStyle())
			.type(captchaProperties.getType())
			.build().finishMap();
		if (StringUtils.isNull(map)) {
			throw new CaptchaException("验证码生成出错，请刷新后重试！");
		}
		// 保存验证码信息
		String code = map.get("code");
		String uuid = IdUtils.fastSimpleUUID();
		String key = CacheConstants.CAPTCHA_CODE_KEY + uuid;
		redisService.setCacheObject(key, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

		result.put("uuid", uuid);
		result.put("img", map.get("imgBase64"));
		return R.ok(result, "操作成功");
	}

	@Override
	public void checkCaptcha(String code, String uuid) throws CaptchaException {
		if (StringUtils.isEmpty(code)) {
			throw new CaptchaException("验证码不能为空");
		}
		if (StringUtils.isEmpty(uuid)) {
			throw new CaptchaException("验证码已失效");
		}
		String key = CacheConstants.CAPTCHA_CODE_KEY + uuid;
		String captcha = redisService.getCacheObject(key);
		redisService.deleteObject(key);
		if (!code.equalsIgnoreCase(captcha)) {
			throw new CaptchaException("验证码错误");
		}
	}
}
